package com.test21_常用类;

import org.junit.Test;

/**
 * 深克隆：与对象有关的引用类型全部进行克隆
 * 浅克隆：只克隆当前类中的基本属性内容
 */
public class Demo06_Cloneable {

    @Test
    public void test1() throws Exception {
        Emp empA = new Emp("李兴华", "软件编程讲师");
        Emp empB = (Emp) empA.clone();  // 对象克隆
        System.out.println(empA);
        System.out.println(empB);
        System.out.println("==============================");
        empB.setEname("爆可爱的小李老师");
        System.out.println(empA);
        System.out.println(empB);
    }

    /** Object类的clone方法，是浅克隆 */
    @Test
    public void test2() throws Exception {
        Dept2 dept = new Dept2("教学研发部", "北京");
        Emp2 empA = new Emp2("李兴华", "软件编程讲师", dept);
        Emp2 empB = (Emp2) empA.clone();    // 对象克隆
        dept.setDname("李兴华编程训练营");
        System.out.println(empA);
        System.out.println("\t|- " + empA.getDept());
        System.out.println("==============================");
        System.out.println(empB);
        System.out.println("\t|- " + empB.getDept());
    }
}

class Emp implements Cloneable {    // 允许克隆
    private String ename;
    private String job;

    public Emp(String ename, String job) {
        this.ename = ename;
        this.job = job;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    @Override
    public String toString() {
        return "【Emp - " + super.toString() + "】姓名：" + this.ename + "、职位：" + this.job;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {   // public使此方法对外部可见
        return super.clone();
    }
}

class Dept2 {
    private String dname;
    private String loc;

    public Dept2(String dname, String loc) {
        this.dname = dname;
        this.loc = loc;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "【Dept - " + super.toString() + "】部门名称：" + this.dname + "、部门位置：" + this.loc;
    }
}

class Emp2 implements Cloneable {
    private String ename;
    private String job;
    private Dept2 dept;

    public Emp2(String ename, String job, Dept2 dept) {
        this.ename = ename;
        this.job = job;
        this.dept = dept;
    }

    public Dept2 getDept() {
        return this.dept;
    }

    @Override
    public String toString() {
        return "【Emp - " + super.toString() + "】姓名：" + this.ename + "、职位：" + this.job;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {   // public使此方法对外部可见
        return super.clone();
    }
}
